<template>
  <div class="meeting-list-container">
    <div class="header">
      <h1>我的会议</h1>
      <button class="create-btn" @click="createNewMeeting">创建会议</button>
    </div>
    
    <div class="meeting-actions">
      <div class="upload-section">
        <input 
          type="file" 
          ref="fileInput"
          style="display: none;"
          @change="handleFileSelect"
          accept=".wav,.mp3,.m4a,.flac,.ogg"
        />
        <button class="upload-btn" @click="$refs.fileInput.click()">
          上传录音文件
        </button>
        <span v-if="selectedFile">已选择: {{ selectedFile.name }}</span>
        <button 
          v-if="selectedFile" 
          class="process-btn"
          @click="processFileUpload"
          :disabled="isUploading"
        >
          {{ isUploading ? '处理中...' : '开始处理' }}
        </button>
      </div>
    </div>
    
    <div class="statistics" v-if="statistics">
      <div class="stat-item">
        <span class="stat-number">{{ statistics.total }}</span>
        <span class="stat-label">总会议数</span>
      </div>
      <div class="stat-item">
        <span class="stat-number">{{ statistics.completed }}</span>
        <span class="stat-label">已完成</span>
      </div>
      <div class="stat-item">
        <span class="stat-number">{{ statistics.processing }}</span>
        <span class="stat-label">处理中</span>
      </div>
      <div class="stat-item">
        <span class="stat-number">{{ statistics.failed }}</span>
        <span class="stat-label">失败</span>
      </div>
    </div>
    
    <div class="meeting-table-container">
      <table class="meeting-table">
        <thead>
          <tr>
            <th>标题</th>
            <th>描述</th>
            <th>文件</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="meeting in meetings" :key="meeting.id">
            <td class="title-cell">{{ meeting.title }}</td>
            <td class="description-cell">{{ meeting.description || '-' }}</td>
            <td class="file-cell">{{ meeting.file_name || '-' }}</td>
            <td>
              <span :class="`status-badge status-${meeting.status.toLowerCase()}`">
                {{ getStatusText(meeting.status) }}
              </span>
            </td>
            <td>{{ formatDate(meeting.created_at) }}</td>
            <td class="actions-cell">
              <button 
                class="view-btn" 
                @click="viewMeeting(meeting.id)"
                :disabled="meeting.status === 'PENDING' || meeting.status === 'PROCESSING'"
              >
                查看
              </button>
              <button 
                class="delete-btn" 
                @click="deleteMeeting(meeting.id)"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>
      
      <div v-if="meetings.length === 0" class="empty-state">
        <p>暂无会议记录</p>
        <p class="empty-hint">点击上方按钮创建会议或上传录音文件</p>
      </div>
    </div>
    
    <!-- 会议标题输入对话框 -->
    <div v-if="showCreateDialog" class="dialog-overlay" @click="closeCreateDialog">
      <div class="dialog" @click.stop>
        <h3>创建新会议</h3>
        <div class="form-group">
          <label for="meeting-title">会议标题</label>
          <input 
            id="meeting-title"
            v-model="newMeetingTitle"
            type="text"
            placeholder="请输入会议标题"
            @keyup.enter="submitCreateMeeting"
          />
        </div>
        <div class="form-group">
          <label for="meeting-description">会议描述（可选）</label>
          <textarea 
            id="meeting-description"
            v-model="newMeetingDescription"
            placeholder="请输入会议描述（可选）"
            rows="3"
          ></textarea>
        </div>
        <div class="dialog-actions">
          <button class="cancel-btn" @click="closeCreateDialog">取消</button>
          <button 
            class="confirm-btn" 
            @click="submitCreateMeeting"
            :disabled="!newMeetingTitle.trim()"
          >
            创建
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MeetingList',
  data() {
    return {
      meetings: [],
      statistics: null,
      selectedFile: null,
      isUploading: false,
      showCreateDialog: false,
      newMeetingTitle: '',
      newMeetingDescription: '',
      // 新增：模拟数据支持相关状态
      useMockData: false,
      mockDataLoaded: false
    }
  },
  mounted() {
    this.fetchMeetings()
    this.fetchStatistics()
  },
  methods: {
    // 新增：加载模拟数据的方法
    async loadMockData() {
      try {
        // 从项目根目录的mock_data文件夹加载模拟数据
        const response = await fetch('/mock_data/meetings.json')
        if (!response.ok) {
          throw new Error('无法加载模拟数据')
        }
        const mockData = await response.json()
        this.meetings = mockData
        this.mockDataLoaded = true
        
        // 根据模拟数据生成统计信息
        this.statistics = {
          total: mockData.length,
          completed: mockData.filter(m => m.status === 'COMPLETED').length,
          processing: mockData.filter(m => m.status === 'PROCESSING').length,
          failed: mockData.filter(m => m.status === 'FAILED').length
        }
        
        console.log('已加载模拟数据:', mockData.length, '条会议记录')
      } catch (error) {
        console.error('加载模拟数据失败:', error)
      }
    },
    
    async fetchMeetings() {
      try {
        const response = await fetch('/api/v1/meetings', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        })
        
        if (!response.ok) {
          throw new Error('获取会议列表失败')
        }
        
        const data = await response.json()
        this.meetings = data
      } catch (error) {
        console.error('获取会议列表错误:', error)
        
        // 新增：如果API调用失败，尝试加载模拟数据
        if (!this.useMockData && !this.mockDataLoaded) {
          console.log('API调用失败，尝试加载模拟数据...')
          this.useMockData = true
          await this.loadMockData()
          // 只提示一次，避免频繁弹窗
          alert('提示：API服务可能未启动，已使用模拟数据进行展示')
        }
      }
    },
    
    async fetchStatistics() {
      try {
        const response = await fetch('/api/v1/meetings/statistics', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        })
        
        if (!response.ok) {
          throw new Error('获取统计信息失败')
        }
        
        const data = await response.json()
        this.statistics = data
      } catch (error) {
        console.error('获取统计信息错误:', error)
        // 如果使用模拟数据且统计信息为空，则重新生成统计信息
        if (this.useMockData && this.meetings.length > 0) {
          this.statistics = {
            total: this.meetings.length,
            completed: this.meetings.filter(m => m.status === 'COMPLETED').length,
            processing: this.meetings.filter(m => m.status === 'PROCESSING').length,
            failed: this.meetings.filter(m => m.status === 'FAILED').length
          }
        }
      }
    },
    
    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.selectedFile = file
      }
    },
    
    async processFileUpload() {
      if (!this.selectedFile) {
        alert('请先选择文件')
        return
      }
      
      // 如果使用模拟数据，提示用户功能受限
      if (this.useMockData) {
        alert('提示：当前使用模拟数据模式，上传功能暂时不可用')
        return
      }
      
      // 获取会议标题（可以根据需要从文件名提取或弹出输入框）
      const title = prompt('请输入会议标题:', this.selectedFile.name)
      if (!title) {
        return
      }
      
      this.isUploading = true
      
      try {
        const formData = new FormData()
        formData.append('file', this.selectedFile)
        formData.append('title', title)
        formData.append('description', '') // 可以根据需要添加描述
        
        const response = await fetch('/api/v1/meetings/upload', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          },
          body: formData
        })
        
        if (!response.ok) {
          throw new Error('上传文件失败')
        }
        
        // 上传成功后刷新会议列表
        this.fetchMeetings()
        this.fetchStatistics()
        
        alert('文件上传成功，正在处理录音...')
        this.selectedFile = null
      } catch (error) {
        console.error('上传文件错误:', error)
        alert('文件上传失败，请重试')
      } finally {
        this.isUploading = false
      }
    },
    
    viewMeeting(meetingId) {
      this.$router.push(`/meeting/${meetingId}`)
    },
    
    async deleteMeeting(meetingId) {
      // 如果使用模拟数据，提示用户功能受限
      if (this.useMockData) {
        alert('提示：当前使用模拟数据模式，删除功能暂时不可用')
        return
      }
      
      if (!confirm('确定要删除这个会议吗？')) {
        return
      }
      
      try {
        const response = await fetch(`/api/v1/meetings/${meetingId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`
          }
        })
        
        if (!response.ok) {
          throw new Error('删除会议失败')
        }
        
        // 删除成功后刷新会议列表
        this.fetchMeetings()
        this.fetchStatistics()
        alert('会议已成功删除')
      } catch (error) {
        console.error('删除会议错误:', error)
        alert('删除会议失败，请重试')
      }
    },
    
    createNewMeeting() {
      // 如果使用模拟数据，提示用户功能受限
      if (this.useMockData) {
        alert('提示：当前使用模拟数据模式，创建功能暂时不可用')
        return
      }
      
      this.showCreateDialog = true
      this.newMeetingTitle = ''
      this.newMeetingDescription = ''
    },
    
    closeCreateDialog() {
      this.showCreateDialog = false
    },
    
    async submitCreateMeeting() {
      if (!this.newMeetingTitle.trim()) {
        alert('请输入会议标题')
        return
      }
      
      try {
        const response = await fetch('/api/v1/meetings', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('access_token')}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            title: this.newMeetingTitle,
            description: this.newMeetingDescription
          })
        })
        
        if (!response.ok) {
          throw new Error('创建会议失败')
        }
        
        // 创建成功后刷新会议列表
        this.fetchMeetings()
        this.fetchStatistics()
        
        this.closeCreateDialog()
      } catch (error) {
        console.error('创建会议错误:', error)
        alert('创建会议失败，请重试')
      }
    },
    
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待处理',
        'PROCESSING': '处理中',
        'COMPLETED': '已完成',
        'FAILED': '失败'
      }
      return statusMap[status] || status
    },
    
    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style scoped>
.meeting-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  color: #333;
}

.create-btn {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.create-btn:hover {
  background-color: #45a049;
}

.meeting-actions {
  margin-bottom: 20px;
}

.upload-section {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.upload-btn, .process-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.upload-btn {
  background-color: #2196F3;
  color: white;
}

.upload-btn:hover {
  background-color: #1976D2;
}

.process-btn {
  background-color: #FF9800;
  color: white;
}

.process-btn:hover:not(:disabled) {
  background-color: #F57C00;
}

.process-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.statistics {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  flex: 1;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.meeting-table-container {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.meeting-table {
  width: 100%;
  border-collapse: collapse;
}

.meeting-table th, .meeting-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.meeting-table th {
  background-color: #f2f2f2;
  font-weight: 600;
  color: #333;
}

.title-cell {
  font-weight: 500;
}

.description-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-cell {
  font-size: 14px;
  color: #666;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background-color: #FFF3CD;
  color: #856404;
}

.status-processing {
  background-color: #E3F2FD;
  color: #1565C0;
}

.status-completed {
  background-color: #D4EDDA;
  color: #155724;
}

.status-failed {
  background-color: #F8D7DA;
  color: #721C24;
}

.actions-cell {
  display: flex;
  gap: 8px;
}

.view-btn, .delete-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.view-btn {
  background-color: #2196F3;
  color: white;
}

.view-btn:hover:not(:disabled) {
  background-color: #1976D2;
}

.view-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.delete-btn {
  background-color: #f44336;
  color: white;
}

.delete-btn:hover {
  background-color: #d32f2f;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-hint {
  font-size: 14px;
  margin-top: 10px;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  min-width: 400px;
}

.dialog h3 {
  margin-top: 0;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input, .form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.cancel-btn, .confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #333;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.confirm-btn {
  background-color: #4CAF50;
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background-color: #45a049;
}

.confirm-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>